global.Moods = db.collection("Moods");
module.exports = {
    get: function(req, res) {
        var data = req.query;
        co(function*(data) {
            var count = yield Moods.count();
            var docs = [];
            if (!count) {
                console.log("no data");
                res.send({});
                return;
            };
            if (count > 7) {
                docs = yield Moods.find({}).skip(count - 7).limit(7).toArray();
            } else {
                docs = yield Moods.find({}).limit(7).toArray();
            };
            docs.length ? (docs = docs) : (docs = {});
            console.log(new Date().toLocaleString(), ":get Moods success");
            res.send(docs);
        }).catch(e => {
            console.log(e);
            res.send({});
        });
    },
    post: function(req, res) {
        var data = req.body;
        if (!data) {
            console.log("none");
            return;
        };
        data.time = new Date().getTime();
        // data.time = new Date().getTime() - 24 * 60 * 60 * 1000;
        co(function*() {
            var r = yield Moods.insertOne(data);
        }).catch(e => {
            console.log("post:")
            console.log(e);
            res.send({});
        });
        res.send(data);
    },
    put: function(req, res) {
        console.log(req.body);
        co(function*(argument) {
            var doc = yield Moods.findOneAndUpdate({ _id: new ObjectId(req.body._id) }, { $set: { Mood: req.body.mood } });
            console.log(doc);
            res.send(doc);
            res.end();
        }).catch(e => {
            console.log(e)
        });
    },
    delete: function(req, res) {
        res.end();
    }
};
